package com.qumitech.visualnovel.service.shop.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.exception.BusinessException;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.common.ResultEnum;
import com.qumitech.visualnovel.controller.vo.shop.ShopAdminAuditDTO;
import com.qumitech.visualnovel.controller.vo.shop.ShopOrderQuery;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.pubdef.dto.Shop.SupplememtDTO;
import com.qumitech.visualnovel.pubdef.pubenum.ItemTypeEnum;
import com.qumitech.visualnovel.service.shop.ShopService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@SuppressWarnings("unchecked")
public class ShopServiceImpl implements ShopService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    private static final String SHOWID_CONVERT_UID = "/account/admin/query/uid";
    private static final String PLAYER_LIST_URL = "/account/admin/information";
    private static final String auditAppealUrl = "/shop/admin/audit";


    @Override
    public Map<String, Object> getOrders(ShopOrderQuery query) {
        String url = UrlConstant.SERVER_URL + "/shop/admin/order/list";
        //拆分渠道
        if (query.getAppChannel() != null && query.getAppChannel().contains(":")) {
            String[] channels = query.getAppChannel().split(":");
            query.setAppChannel(channels[0]);
            query.setSubAppChannel(channels[1]);
        }

        String req = JSONObject.toJSONString(query);

        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()
                || rsp.getData() == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }

        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        if (rspMap.get("orders") == null || rspMap.get("count") == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        return rspMap;
    }

    @Override
    public void supplementOrder(String oid, String remark) {
        String url = UrlConstant.SERVER_URL + "/shop/order/" + oid + "/supplement";
        JSONObject o = new JSONObject();
        o.put("remark", remark);
        String body = HttpInvokeUtil.httpPutJson(url, o, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
    }

    @Override
    public void addSupplememt(SupplememtDTO supplememtDTO) {
        String url = UrlConstant.SERVER_URL + "/shop/order/supplement";
        supplememtDTO.setGoodType(ItemTypeEnum.getItemTypeEnum(supplememtDTO.getItemType().intValue()).getGoodType());
        String reqBody = JSONObject.toJSONString(supplememtDTO);
        String body = HttpInvokeUtil.httpPostJson(url, reqBody, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
    }

    @Override
    public void saveReward(JSONObject param) {
        String url = UrlConstant.SERVER_URL + "/account/prop";
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        param.put("operator", activeUser.getUsername());
        JSONArray postArray = param.getJSONArray("uids");
        JSONObject postData = new JSONObject();
        postData.put("present_ids", postArray);
        String body = HttpInvokeUtil.httpPostJson(UrlConstant.SERVER_URL + SHOWID_CONVERT_UID, postData.toJSONString(), UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        JSONObject data = (JSONObject) rsp.getData();
        param.put("uids", data.getJSONArray("uid_array"));
        body = HttpInvokeUtil.httpPostJson(url, param.toJSONString(), UrlConstant.DefaultEncode, null);
        rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
    }

    @Override
    public BaseRsp rewardUserInfo(JSONObject param) {
        JSONArray postArray = param.getJSONArray("uids");
        JSONObject postData = new JSONObject();
        postData.put("present_ids", postArray);
        String body = HttpInvokeUtil.httpPostJson(UrlConstant.SERVER_URL + SHOWID_CONVERT_UID, postData.toJSONString(), UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        JSONObject data = (JSONObject) rsp.getData();
        postData.put("list_uid", data.getJSONArray("uid_array"));
        body = HttpInvokeUtil.httpPostJson(UrlConstant.SERVER_URL + PLAYER_LIST_URL, JSONObject.toJSONString(postData), UrlConstant.DefaultEncode, null);
        rsp = JSONObject.parseObject(body, BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseRsp getRewardList(String operator, Long uid, Integer propType, Integer changeType, String startTime, String endTime, Integer offset, Integer limit) {
        String url = UrlConstant.SERVER_URL + "/account/admin/prop/list";
        Map<String, String> paramMap = new HashMap<>();
        if (offset != null) {
            paramMap.put("offset", offset.toString());
        }
        if (limit != null) {
            paramMap.put("limit", limit.toString());
        }
        if (operator != null) {
            paramMap.put("operator", operator);
        }
        if (uid != null) {
            paramMap.put("uid", uid.toString());
        }
        if (propType != null) {
            paramMap.put("prop_type", propType.toString());
        }
        if (changeType != null) {
            paramMap.put("change_type", changeType.toString());
        }
        if (startTime != null) {
            paramMap.put("startTime", startTime);
        }
        if (endTime != null) {
            paramMap.put("endTime", endTime);
        }
        String body = HttpInvokeUtil.httpGet(url, paramMap, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()
                || rsp.getData() == null) {
            throw new BusinessException(ResultEnum.FAILURE);
        }
        return rsp;
    }

    @Override
    public BaseRsp audit(ShopAdminAuditDTO param) {
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        param.setOperator(activeUser.getUsername());
        String url = String.format("%s%s", UrlConstant.SERVER_URL, auditAppealUrl);
        String req = JSONObject.toJSONString(param);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }
}
